package com.histone.heartbeat.service;

import com.alibaba.fastjson.JSONObject;
import com.histone.heartbeat.pojo.WxApi;
import com.histone.heartbeat.pojo.WxProperties;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.time.LocalTime;

@Service
@Slf4j
public class TokenService {
    @Getter
    private String token;

    @Autowired
    private WxApi wxApi;

    @Autowired
    private WxProperties wxProperties;

    @Autowired
    private RestTemplate restTemplate;

    @Scheduled(fixedRate = 6600000L)
    public void setToken(){
        String token_url = wxApi.getAccess_token()
                .replaceAll("APPID", wxProperties.getAppid())
                .replaceAll("SECRET", wxProperties.getSecret());

        JSONObject result = restTemplate.getForObject(token_url, JSONObject.class);
        this.token = result.getString("access_token");
        log.info("get token {} at {}", this.token, LocalTime.now());
    }
}
